package crp.services.api.graphql;

import com.qwlabs.jackson.Jackson;
import com.qwlabs.storage.StorageService;
import crp.core.security.Callers;
//import crp.core.storage.app.StorageObjectService;
import com.qwlabs.storage.services.StorageContext;
import crp.services.api.graphql.models.CompleteUploadInput;
import crp.services.api.graphql.models.CreateUploadUrlsInput;
import crp.services.api.graphql.models.UploadUrlsPayload;
import io.quarkus.security.identity.SecurityIdentity;
import org.eclipse.microprofile.graphql.GraphQLApi;
import org.eclipse.microprofile.graphql.Mutation;

import javax.annotation.security.PermitAll;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Map;

@GraphQLApi
@RequestScoped
public class StorageGraphQLApi {

    private final StorageService storageService;
    private final SecurityIdentity securityIdentity;

    @Inject
    public StorageGraphQLApi(StorageService storageService,
                             SecurityIdentity securityIdentity) {
        this.storageService = storageService;
        this.securityIdentity = securityIdentity;
    }

    @Mutation
    @PermitAll
    @NotNull
    public UploadUrlsPayload createUploadUrls(@NotNull @Valid CreateUploadUrlsInput input) {
        Map context = Jackson.read(input.getContext(), Map.class).orElse(null);
        StorageContext storageContext = new StorageContext(input.getBusinessType(), context);
        storageContext.setUserId(Callers.userId());
        return UploadUrlsPayload.of(storageService.createUploadUrls(storageContext));
    }

    @Mutation
    @PermitAll
    @NotNull
    public String completeUpload(@NotNull @Valid CompleteUploadInput input) {
        return storageService.completeUpload(input.of());
    }

}
